import { Disease } from '../../types/disease'
import { execute, select } from '../../utils/db'
import { Page, PageReq } from '../../types/page'

export class DiseaseDao {
  /**
   * 创建疾病
   */
  static async create(disease: Omit<Disease, 'id'>): Promise<number | undefined> {
    const result = await execute(
      'INSERT INTO disease (name) VALUES (?) RETURNING id',
      [disease.name]
    )
    return result?.lastInsertId
  }

  /**
   * 更新疾病信息
   */
  static async update(disease: Partial<Disease>): Promise<void> {
    console.log('disease',disease)
    if (disease.name) {
      await execute(
        'UPDATE disease SET name = ? WHERE id = ?',
        [disease.name, disease.id]
      )
    }
  }

  /**
   * 删除疾病
   */
  static async delete(id: number): Promise<void> {
    await execute('DELETE FROM disease WHERE id = ?', [id])
  }

  /**
   * 获取疾病详情
   */
  static async getById(id: number): Promise<Disease> {
    const result = await select<Disease>(
      'SELECT * FROM disease WHERE id = ? LIMIT 1',
      [id]
    )
    return result[0]
  }

  /**
   * 获取疾病列表
   */
  static async list(): Promise<Disease[]> {
    const result = await select<Disease[]>('SELECT * FROM disease')
    return result
  }

  /**
   * 分页查询疾病列表
   */
  static async page(params: PageReq<Disease>): Promise<Page<Disease>> {
    const { pageNum, pageSize } = params
    const offset = (pageNum - 1) * pageSize
    const disease = params.params
    
    const condition = disease.name ? 'WHERE name LIKE ?' : ''
    const values = disease.name ? [`%${disease.name}%`] : []

    const [totalResult, listResult] = await Promise.all([
      select('SELECT COUNT(*) as count FROM disease ' + condition, values),
      select(`SELECT * FROM disease ${condition} LIMIT ${pageSize} OFFSET ${offset}`, values)
    ])

    return {
      total: totalResult[0].count || 0,
      list: (listResult as unknown as Disease[]) || []
    }
  }
}